<?php
/**
 * Created by openXtiger.org.
 * User: lunzi
 * Date: 2009-6-27
 * Time: 17:22:49
 */
define('CATEGORY_TREE_SQL',xt_tname('category').' join '.xt_tname('tree'). ' on tree_id=tid and bid=rid ');
/*public */function categorymodel_findCategoryByPId($pid,$tradeType='') {
    $db = xt_load('db');
    $query = $db->query('select '.(empty($tradeType)?'':'if(tradeType=0,id,tradeType)').' id,name from '.xt_tname('category').' where pid='.$pid);
    $result = array();
    while ($row = $db->fetch_array($query)) {
        $result[] = $row;
    }
    return $result;
}
/*public */function categorymodel_findCategoryPath($id) {
    $db = xt_load('db');
    $r = categorymodel_getTreeNode($id);
    if($r) {
        $query = $this->db->query( 'SELECT id,name FROM '.CATEGORY_TREE_SQL."  WHERE  lft<={$r['lft']} AND rgt>={$r['rgt']} AND bid={$r['bid']} order by lft");
        $result = array();
        while ($row = $this->db->fetch_array($query)) {
            $result[] = $row;
        }
        return $result;
    }
    return array();
}
/*public */function categorymodel_findCategoryByKey($keyword) {
    $keyword = addslashes($keyword);
    $db = xt_load('db');
    $query = $db->query('select id,name from '.xt_tname('category').' where pid=0');

    $pr = array();
    while ($row = $db->fetch_array($query)) {
        $pr[$row['id']] = $row['name'];
    }
    $query = $db->query('select id,name,pid,rid from '.CATEGORY_TREE_SQL." where rgt=lft+1 and name like '%$keyword%' or fspell like '%$keyword%' limit 10");
    $result = array();
    while ($row = $db->fetch_array($query)) {
        $result[] = array('id'=>$row['id'],'path'=>( $pr[$row['rid']]. (isset($pr[$row['pid']])?' &gt; ':' &gt;..&gt; ').$row['name'] ));
    }
    return $result;   
}
/*public */function categorymodel_getTreeNode($id) {
    $db = xt_load('db');
    if($id==0) {
        return $db->fetch_first('SELECT lft,rgt,tid,bid FROM '.xt_tname('tree').' WHERE lft = 1');
    }
    return $db->fetch_first('SELECT lft,rgt,tid,bid FROM '.CATEGORY_TREE_SQL.' WHERE id = '.$id);
}

/*public */function categorymodel_findCategoryById($id) {
    $db = xt_load('db');
    return $db->fetch_first("SELECT * FROM `icweb_category` WHERE id= '$id'");
}
?>